$(function () {
  init()

  analytics.send({
    event: `${avPrefix}_open`
  })

  if (new Date().getTime() > 1539187199000) {
    $('#buy').hide()
    $('#stop').show()
    return
  }

  getBuyInfo()

  function getBuyInfo () {
    account.forceLogin = false
    account.getUserInfo((err, userInfo) => {
      if (err) {
        // 没有登录, 肯定也不会有购买了
        // 那就什么都不做, 显示购买界面
        console.log('未登录')
        setBuyStatus(0)
      } else {
        // 已经登录, 那就要先判断自己是否已经购买
        activeShare(userInfo.shareFlag)
        checkBuying(
          () => {
            console.log('未购买')
            setBuyStatus(0)
          },
          () => {
            console.log('已购买')
            setBuyStatus(2)
          }
        )
      }
    })
  }

  function checkBuying (unbuying, buying) {
    account.ajax({
      type: 'GET',
      path: `/s/my/products/1036/detail`,
      success: product1 => {
        account.ajax({
          type: 'GET',
          path: `/s/my/products/1041/detail`,
          success: product2 => {
            account.ajax({
              type: 'GET',
              path: `/s/my/products/1043/detail`,
              success: product3 => {
                if (!product1.total && !product2.total && !product3.total) {
                  unbuying()
                } else {
                  buying()
                }
              },
              error: err => console.error(err)
            })
          },
          error: err => console.error(err)
        })
      },
      error: err => console.error(err)
    })
  }

  function setBuyStatus (status) {
    window.buyStatus = status
    switch (status) {
      case 2: {
        // 显示分享
        // 有登录, 但是购买过19.9的活动的, 忽略referenceCode
        $('#buy').text('分享给好友')
        break
      }
      case 0:
      default: {
        // 显示购买
        $('#buy').text('立即购买')
      }
    }
  }

  function submitOrder (pid) {
    account.forceLogin = true
    //提交订单久趣后台
    account.getUserInfo((err, userInfo) => {
      if (err) {
        $.toastAlert(err.message)
        return
      }
      activeShare(userInfo.shareFlag)
      const payChannel = utils.isWeChat() ? 'weixin' : 'alipay'
      const openId = window.localStorage.getItem(account.openId)
      activeShare(userInfo.shareFlag)
      checkBuying(
        () => {
          account.ajax({
            type: 'GET',
            path: `/s/customers/${openId}/status`,
            success: status => {
              account.ajax({
                type: 'POST',
                path: '/s/bills',
                data: {
                  productId: pid,
                  payChannel: payChannel,
                  returnUrl: status.subscribe ? `${campUrl}${Math.ceil(Math.random() * 100)}` : `${verifyUrl}`,
                  tradeType: 'JSAPI',
                  openId: openId
                },
                success: data => {
                  if (data.status !== 'error') {
                    analytics.send({
                      event: `${avPrefix}_buy`,
                      attr: {
                        pid: pid,
                        payChannel: payChannel
                      }
                    })
                    if (utils.isWeChat()) {
                      const jsApiParameters = JSON.parse(data.jsApiParameters)
                      jsApiParameters.redirect = status.subscribe ? `${campUrl}${Math.ceil(Math.random() * 100)}` : `${verifyUrl}`

                      // 唤起微信支付
                      wxconfig.pay(data.bill_id, pid, jsApiParameters, encodeURIComponent(campUrl))
                    } else {
                      // 跳转去支付宝支付
                      window.location.href = data.url
                    }
                  } else {
                    $.toastAlert('下单失败，请重试')
                  }
                },
                error: err => {
                  if (err.code === 'product.rejected.by.bought.products') {
                    utils.alert('您已购买过自然拼读体验课')
                    getBuyInfo()
                  } else if (err.code === 'product.rejected.by.bought.products') {
                    $.toastAlert('您已经参加活动', 2)
                  } else {
                    $.toastAlert(err.message, 2)
                  }
                }
              })
            },
            error: err => $.toastAlert(err.message, 2)
          })
        },
        () => {
          setBuyStatus(2)
          utils.alert('您已经购买过自然拼读体验课，可以点击右上角分享给朋友哦')
        }
      )
    })
  }

  $('.level-buttons > div').off('click').on('click', e => {
    $('.level').attr('class', 'level ' + e.target.className)
  })

  // 点击购买按钮
  $('#buy').off('click').on('click', () => {
    debugger
    if (buyStatus) $('.share-mask').fadeIn()
    else submitOrder($('#buy').attr('data-pid'))
  })

  // 关闭分享提示
  $('.share-mask').click(() => {
    $('.share-mask').fadeOut()
  })

  // 切换账号
  $('#switch-account').off('click').on('click', () => {
    $('.account-mask').fadeOut()
    account.forceLogin = true
    account.checkLoginStatus(() => {
      account._showLogin(() => {
        console.log('登录成功, 刷新数据')
        getBuyInfo()
      }, true)
    })
  })
})

function init () {
  window.campaign = 'phonicsextra'
  window.campUrl = `${window.location.protocol}//${window.location.host}/wx/phonics`
  window.verifyUrl = `${campUrl}/verifypayment?type=2`
  window.avPrefix = 'p005'
  window.analytics = AV.analytics({
    appId: 'antYy9lOFi5mkU9QKjtYmRLM-gzGzoHsz',
    appKey: 'jqyWxLyobpsmdwsJddJlDheb',
    channel: utils.isWeChat() ? 'weixin' : ''
  })
  window.wxconfig = new WxConfig(wechatConfig, window.campaign)
  window.account = new Account()
  window.shareFlag = ''
  window.shareMsg = shareFlag => {
    return {
      title: '久趣19.9元4节体验课, 在家和北美外教学【自然拼读】',
      desc: '北美外教在线教学，让孩子轻松认读新单词！',
      link: `${campUrl}${Math.ceil(Math.random() * 100)}?_c=${window.campaign}&_r=${shareFlag}`,
      imgUrl: 'https://static-app.97kid.com/site-student/public/img/share.png',
      success: target => {
        analytics.send({
          event: `${avPrefix}_share_success`,
          attr: {
            target: target
          }
        })
      }
    }
  }
  window.activeShare = shareFlag => {
    if (utils.isWeChat()) window.shareFlag = shareFlag || ''
    wxconfig.activeShare(shareFlag, '', shareMsg(shareFlag))
  }
  if (!utils.getUrlParam('_c')) {
    const QKidsChannel = JSON.parse(window.localStorage.getItem('QKidsChannel'))
    if (!(QKidsChannel && QKidsChannel.expires > new Date().getTime() / 1000)) {
      window.localStorage.setItem('QKidsChannel', JSON.stringify({
        rawData: `${campaign}_share`,
        expires: new Date().getTime() / 1000 + 24 * 3600
      }))
    }
  }
}